using System;
using System.Web.UI.WebControls;
using DotNetNuke.UI.Containers;

namespace HeroldIT.Dnn.SkinHelpers
{
    /// <summary>
    /// Defines extension methods for the <see cref="Container"/> class.
    /// </summary>
    public static class ContainerExtensions
    {
        /// <summary>
        /// Checks, whether the given container is the first container in the containing pane.
        /// </summary>
        /// <param name="container">The <see cref="Container"/> to check.</param>
        /// <returns><c>true</c> if the container is the first in the pane; otherwise <c>false</c>.</returns>
        public static bool IsFirstContainerInPane(this Container container)
        {
            if (null == container)
                throw new ArgumentNullException("container");

            var isFirstContainerInPane = true;

            if (container.Parent is Panel) // this occurs in admin-mode, where each container is wrapped in its own Panel
            {
                var controlIndex = container.Parent.Parent.Controls.IndexOf(container.Parent);

                for (var i = controlIndex - 1; i >= 0; i--)
                {
                    var panel = container.Parent.Parent.Controls[i] as Panel;
                    if (null == panel) continue;
                    if (panel.Controls.Count <= 0) continue;
                    if (!(panel.Controls[0] is Container)) continue;

                    isFirstContainerInPane = false;
                    break;
                }
            }
            else // not in admin mode, the containers are directly situated in the pane
            {
                var controlIndex = container.Parent.Controls.IndexOf(container);

                for (var i = controlIndex - 1; i >= 0; i--)
                {
                    if (!(container.Parent.Controls[i] is Container)) continue;

                    isFirstContainerInPane = false;
                }
            }

            return isFirstContainerInPane;
        }
    }
}
